package com.example.myserver.pdf;

import org.springframework.stereotype.Service;
import org.apache.pdfbox.pdmodel.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

@Service
public class PdfService {

    /**
     * 删除PDF中指定范围的页面
     * @param inputFile 输入PDF文件
     * @param outputFile 输出PDF文件
     * @param startPage 开始删除的页码（从1开始）
     * @param endPage 结束删除的页码
     * @throws IOException
     */
    public void deletePages(File inputFile, File outputFile, int startPage, int endPage) throws IOException {
        try (PDDocument document = PDDocument.load(inputFile)) {
            int totalPages = document.getNumberOfPages();

            // 验证页码范围
            if (startPage < 1 || endPage > totalPages || startPage > endPage) {
                throw new IllegalArgumentException("无效的页码范围");
            }

            // 从后往前删除，避免索引变化
            for (int i = endPage; i >= startPage; i--) {
                document.removePage(i - 1); // PDFBox页码从0开始
            }

            document.save(outputFile);
        }
    }

    /**
     * 处理输入流并返回输出流
     */
    public void deletePages(InputStream inputStream, OutputStream outputStream,
                            int startPage, int endPage) throws IOException {
        try (PDDocument document = PDDocument.load(inputStream)) {
            int totalPages = document.getNumberOfPages();

            if (startPage < 1 || endPage > totalPages || startPage > endPage) {
                throw new IllegalArgumentException("无效的页码范围");
            }

            for (int i = endPage; i >= startPage; i--) {
                document.removePage(i - 1);
            }

            document.save(outputStream);
        }
    }

    public static void main(String[] args) {
        PdfService pdfService = new PdfService();
        try {
            final String source = "C:\\Users\\Jiangxiaomin\\Desktop\\新建文件夹\\（01）方法精讲-言语-郭熙【完】\\source.pdf";
            final String target = "C:\\Users\\Jiangxiaomin\\Desktop\\新建文件夹\\（01）方法精讲-言语-郭熙【完】\\target.pdf";
            pdfService.deletePages(new File(source), new File(target), 2, 69);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
